package com.duda.util;

import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import com.gargoylesoftware.htmlunit.util.NameValuePair;

import java.io.IOException;
import java.net.URL;
import java.util.*;

public class GetDownloadUrlForNT {
    private static WebClient mWebClient = new WebClient();
    private static final int timeOut = 100;
    private static final int jsLoadTime = 30;
    private static final String loginUrl = "https://login.nipic.com/login";
    private static final String downloadUrl = "http://down.nipic.com/ajax/download_go";

    public static void LoginNT() throws IOException {
        mWebClient.getOptions().setJavaScriptEnabled(true);
        mWebClient.getOptions().setThrowExceptionOnScriptError(true);
        mWebClient.getOptions().setCssEnabled(false);

        mWebClient.getOptions().setRedirectEnabled(true);
        mWebClient.getOptions().setTimeout(timeOut* 1000);
        mWebClient.setJavaScriptTimeout(timeOut* 1000);
        mWebClient.waitForBackgroundJavaScript(jsLoadTime * 1000);
        mWebClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        mWebClient.getOptions().setUseInsecureSSL(true);
        mWebClient.getCookieManager().setCookiesEnabled(true);

        HtmlPage page = mWebClient.getPage(loginUrl);
        List<HtmlForm> forms = page.getForms();
        for (int i=0; i< forms.size(); i++) {
            HtmlForm form = forms.get(i);
            String id = form.getId();
            if("loginForm".equals(id)) {
                HtmlTextInput textUserName = form.getInputByName("UserName");
                textUserName.setText("yijuyanyue");
                HtmlPasswordInput textPwd = form.getInputByName("PassWord");
                textPwd.setText("758521@");

                HtmlSubmitInput login = (HtmlSubmitInput) page.getByXPath("//*[@id=\"login\"]/li[5]/input").get(0);
                login.click();
            }
        }

    }

    private static int requestLoginIndex = 0 ;
    public static synchronized String getDownloadUrl(String url) throws Exception {
        HtmlPage downPage = mWebClient.getPage(url);
        List<Object> byXPath = downPage.getByXPath("//*[@id=\"showMore\"]/div[2]/div[4]/text/a");
        List<Object> byXPath1 = downPage.getByXPath("//*[@id=\"showMore\"]/div[2]/div/div/ul/li[1]/div[1]/input");
        if(byXPath.size() > 0){
            HtmlAnchor downloadButton = (HtmlAnchor)byXPath.get(0);
            List<Object> byXPath2 = downPage.getByXPath("/html/body/div[3]/input[1]");
            List<Object> byXPath3 = downPage.getByXPath("//*[@id=\"J_worksId\"]");
            List<Object> byXPath4 = downPage.getByXPath("//*[@id=\"showMore\"]/div[2]/div[4]/text/a");
            HtmlHiddenInput __RequestVerificationToken = (HtmlHiddenInput) byXPath2.get(0);
            HtmlHiddenInput id = (HtmlHiddenInput)byXPath3.get(0);
            HtmlAnchor kid = (HtmlAnchor) byXPath4.get(0);
            String kidStr = kid.getAttribute("data-line");
            String defaultValue = __RequestVerificationToken.getDefaultValue();
            String defaultValueId = id.getDefaultValue();
            WebRequest request = new WebRequest(new URL(downloadUrl), HttpMethod.POST);
            Map<String, String> additionalHeaders = new HashMap<String, String>();
            additionalHeaders.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            List<NameValuePair> list = new ArrayList<>();
            list.add(new NameValuePair("id",defaultValueId));
            list.add(new NameValuePair("kid",kidStr));
            list.add(new NameValuePair("__RequestVerificationToken",defaultValue));
            request.setRequestParameters(list);

            Page page = mWebClient.getPage(request);
            String contentAsString = page.getWebResponse().getContentAsString();
            JSONObject jsonObject = JSONObject.parseObject(contentAsString);
             return jsonObject.getJSONObject("data").getString("url");
//            Page pageButton = downloadButton.click();
//            WebResponse webResponse = pageButton.getWebResponse();
//            requestLoginIndex = 0;
//            return webResponse.getWebRequest().getUrl().toString();
        } else {
            if( requestLoginIndex == 0 && byXPath1.size() == 0) {
                try {
                    LoginNT();
                }catch (Exception e) {
                    e.printStackTrace();
                }
                getDownloadUrl(url);
                requestLoginIndex++;
            } else {
               return "000000";
            }
        }

       return "";

    }

}
